<template>
  <div>
    <!--    1.第一层-->
    <div class="card-container">
      <!--1.-->
      <div class="time-card">
        <el-card shadow="hover" class="card colorful-card">
          <div class="time-info">
            <h1 style="font-size: 22px;">Hi {{ role.name }}, {{ greeting }}</h1>
            现在时间: {{ currentTime | dateFormat }}
          </div>
        </el-card>
      </div>

      <template>
        <el-card shadow="hover" class="card">
          <div class="card-content">
            <div class="icon-container">
              <i class="iconfont icon-dingdanliang-" style="color: #0056b3;"></i>
            </div>
            <div class="text-container">
              <span class="card-title">订单数量</span>
              <div class="card-data">{{ orderCount }}</div>
            </div>
          </div>
        </el-card>
      </template>

      <template>
        <el-card shadow="hover" class="card">
          <div class="card-content">
            <div class="icon-container">
              <i class="iconfont icon-zhuceliang" style="color: #7DCEA0;"></i>
            </div>
            <div class="text-container">
              <span class="card-title">用户数量</span>
              <div class="card-data">{{ registeredUsers }}</div>
            </div>
          </div>
        </el-card>
      </template>

      <template>
        <el-card shadow="hover" class="card">
          <div class="card-content">
            <div class="icon-container">
              <i class="iconfont icon-shangpinshuliang" style="color: #99a9bf;"></i>
            </div>
            <div class="text-container">
              <span class="card-title">商品数量</span>
              <div class="card-data">{{ productCount }}</div>
            </div>
          </div>
        </el-card>
      </template>

      <template>
        <el-card shadow="hover" class="card">
          <div class="card-content">
            <div class="icon-container">
              <i class="iconfont icon-xiaoshoue" style="color: #7d7bd1;"></i>
            </div>
            <div class="text-container">
              <span class="card-title">销售额</span>
              <div class="card-data">{{ totalSalesAmount }}</div>
            </div>
          </div>
        </el-card>
      </template>

    </div>
    <!-- 添加间隔 -->
    <div style="height: 10px;"></div>

    <!--    2.第二层-->
    <div class="custom-canvas-container">
      <el-card shadow="hover" class="left-canvas">
        <div class="chart-container">
          每月销售额（2024）
          <canvas ref="lineChartCanvas" class="left-canvas1" style="width: 500px; height: 300px;"></canvas>
        </div>
      </el-card>

      <el-card shadow="hover">
        <div class="chart-container">
          商品销售排列（Top8）
          <div class="chart" ref="chartContainer"></div>
        </div>
      </el-card>
    </div>

  </div>
</template>

<script>
import Chart from 'chart.js/auto';
import {ref, onMounted} from 'vue';
import * as echarts from 'echarts';

import '@/assets/icon/iconfont.css'
import axios from 'axios';


export default {
  setup() {
    const lineChartCanvas = ref(null);
    let lineChartInstance = null;

    const productSale = async () => {
      const url = '/community/employee/productSale';
      const response = await axios.post(url);
      const data = response.data;

      initChart(data);
    };

    const initChart = (data) => {
      const ctx = lineChartCanvas.value.getContext('2d');
      lineChartInstance = new Chart(ctx, {
        type: 'line',
        data: {
          labels: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
          datasets: [{
            label: '销售额',
            data: data,
            fill: false,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.1
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    };

    productSale();

    const chartContainer = ref(null);

    onMounted(() => {
      const chart = echarts.init(chartContainer.value);

      const hexToRgba = (hex, opacity) => {
        let rgbaColor = "";
        let reg = /^#[\da-f]{6}$/i;
        if (reg.test(hex)) {
          rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
              "0x" + hex.slice(3, 5)
          )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
        }
        return rgbaColor;
      };


      /* 2024年5月30日18:35:43  到时候就将数据
      *   xData：在后端查询为一个数组，最大到小排列10个，然后后面都加一个1
      *   yData：就要在商品表里面多加一个字段了，然后也是获取到
      * */

      let xData = [];
      let yData = [];

      const productSalesTop8 = async () => {
        const url = '/community/product/productSalesTop8';
        try {
          // 发起对 '/community/product/productSalesTop8' 的 HTTP 请求
          const response = await axios.post(url);
          // 假设响应是一个包含字符串的数组
          xData = response.data.xdata; // 确保 response.data.xdata 是数组类型
          yData = response.data.ydata;
        } catch (error) {
          console.error('Error fetching product sales data:', error);
        }
      };

      // 调用这个异步方法
      productSalesTop8();

      // 使用 async/await 确保等待异步操作完成
      (async () => {
        await new Promise(resolve => setTimeout(resolve, 1000)); // 等待一段时间

        let max = Math.max(...yData);
        let labelColor = ['#FD5360', '#FF962B', '#FFAA00'];
        let emptyData = yData.map((v, i) => {
          let color = i > 2 ? '#1890FF' : labelColor[i];
          let item = {
            value: max,
            label: {
              formatter: '{a|' + v + '}',
              position: 'right',
              distance: 20,
              rich: {
                a: {
                  color: color,
                  borderColor: color,
                  borderWidth: 1,
                  borderType: 'dashed',
                  padding: [0, 0, 2, 0],
                  width: 60,
                  height: 18,
                  align: 'center',
                  verticalAlign: 'middle',
                  backgroundColor: hexToRgba(color, 0.05)
                }
              }
            }
          };
          return item;
        });

        let xDataFormat = xData.map((v, i) => {
          let color = i > 2 ? '#333333' : labelColor[i];
          let item = {
            value: v,
            textStyle: {
              rich: {
                a: {
                  color: color,
                  width: 20,
                  height: 20,
                  align: 'center',
                  verticalAlign: 'middle',
                  backgroundColor: '#fff',
                  borderRadius: 10,
                  borderColor: hexToRgba(color, 0.2),
                  borderWidth: 1,
                  shadowColor: hexToRgba(color, 0.1),
                  shadowBlur: 5
                },
                b: {
                  padding: [0, 5]
                },
                value: {
                  color: '#666666'
                }
              }
            }
          };
          return item;
        });

        xData.reverse();
        xDataFormat.reverse();
        yData.reverse();
        emptyData.reverse();

        const option = {
          backgroundColor: '#fff',
          grid: {
            top: '5%',
            left: '1%',
            right: '15%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'value',
            splitLine: {
              show: false
            },
            max: function (value) {
              return value.max;
            },
            axisLine: {
              lineStyle: {
                color: '#D9D9D9'
              }
            },
            axisLabel: {
              color: '#666'
            }
          }],
          yAxis: [{
            type: 'category',
            name: '',
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#D9D9D9'
              }
            },
            axisLabel: {
              formatter: function (value) {
                return '{a|' + value.substr(value.length - 1) + '}{b|}{value|' + value + '}';
              }
            },
            data: xDataFormat
          }, {
            type: 'category',
            name: '',
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              show: false
            },
            axisLine: {
              show: false
            },
            data: xData
          }],
          series: [
            {
              type: 'bar',
              barWidth: 10,
              yAxisIndex: 1,
              itemStyle: {
                normal: {
                  barBorderRadius: [0, 6, 6, 0],
                  color: 'rgba(225,225,225,0.4)'
                }
              },
              label: {
                show: true,
                position: 'right',
                formatter: function (a) {
                  console.log(a);
                }
              },
              data: emptyData
            },
            {
              type: 'bar',
              barWidth: 10,
              zlevel: 1,
              itemStyle: {
                normal: {
                  barBorderRadius: [0, 6, 6, 0],
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    {
                      offset: 0,
                      color: '#3D9FFF'
                    },
                    {
                      offset: 1,
                      color: '#41D7F3'
                    }
                  ], false)
                }
              },
              data: yData
            }
          ]
        };

        chart.setOption(option);

      })();
    });

    return {
      chartContainer,
      lineChartCanvas
    };
  },
  data() {
    return {
      role: {name: "管理员"},
      currentTime: new Date(),
      orderCount: "",
      registeredUsers: "",
      productCount: "", // 商品数量
      totalSalesAmount: "", // 销售额
      xData: [],
      yData: [],
    };

  },

  created() {
    this.productSalesTop8();
    this.getMessage();
  },
  computed: {
    // 1.判断时间
    greeting() {
      const hour = this.currentTime.getHours();
      if (hour < 12) {
        return "早上好";
      } else if (hour < 18) {
        return "下午好";
      } else {
        return "晚上好";
      }
    }
  },
  mounted() {
    setInterval(() => {
      this.currentTime = new Date();
    }, 1000);

  },
  methods: {
    /**
     * 查询如下：
     * 1.订单数量
     * 2.用户数量
     * 3.商品数量
     * 4.销售额
     */
    async getMessage() {
      const url = `/community/menu/`;
      const orderResponse = await this.$http.post(url + "/getOrderQuantity");
      this.orderCount = orderResponse.data;

      const consumerResponse = await this.$http.post(url + "/getConsumerQuantity");
      this.registeredUsers = consumerResponse.data;

      const productResponse = await this.$http.post(url + "/getProductQuantity");
      this.productCount = productResponse.data;

      const salesResponse = await this.$http.post(url + "/getSale");
      this.totalSalesAmount = salesResponse.data;

    },

    async productSalesTop8() {
      const url = `/community/product/productSalesTop8`;
      const respone = await this.$http.post(url);
      this.xData = respone.data.xdata;

    },
  },
};
</script>

<style scoped>
.card-container {
  display: flex;
}

.card {
  flex: 1;
  margin-right: 10px;
}

.colorful-card {
  background-color: #f4b4cf;
  background-image: linear-gradient(to right, #f4b4cf, #c894db, #7d7bd1, #3da3f5);
  color: #333;
}

.card-data {
  font-size: 24px;
  font-weight: bold;
}

.time-info {
  color: white;

  position: relative;
  top: -10px; /* 举例：向下移动50像素 */
  left: 0px; /* 举例：向右移动20像素 */
}

.time-card {
  width: 300px; /* 调整所需的宽度 */

  /* 通过设置位置属性来移动元素 */
  position: relative;
  top: 0px; /* 举例：向下移动50像素 */
  left: 0px; /* 举例：向右移动20像素 */

  /* 调整字体样式 */
  font-family: Arial, sans-serif;
  font-size: 16px;
  font-weight: bold;
  color: #333; /* 文字颜色 */
}

/**/
.card-content {
  display: flex;

  align-items: center; /* 水平居中 */
  height: 100px; /* 举例：设置固定高度为300像素，或者使用百分比设置高度 */
  text-align: center; /* 文本居中 */
}


/* 调整图标大小*/
/*.icon-dingdanliang-, .icon-shangpinshuliang, .icon-zhuceliang, .icon-xiaoshoue {
  font-size: 70px;
  margin-right: 10px;
}*/
.icon-container i {
  font-size: 60px;
  margin-right: 10px;
}


.custom-canvas-container {
  display: flex; /* 使用 Flexbox 布局 */
}

.custom-canvas-container .el-card {
  flex: 1; /* 子元素平均分配空间 */
  margin: 0 2px; /* 为了增加子元素之间的间距，可以调整这个值 */
}

.left-canvas {
  /* 左侧可视化图形的样式 */
  height: 400px;

  position: relative;
  right: 8px;
}

.left-canvas1 {
  width: 100%;
  height: 200%;
  height: 200%;

  position: relative;
  top: 30px;
}

.chart {
  height: 500px;
}

.chart-container {
  text-align: center;
  width: 100%;
  height: 360px;
}

/* 调整Top8 商品销售排行*/
.chart {
  width: 110%;
  height: 90%;

  position: relative;
  right: 80px;
}

</style>

